//
//  YFStatusListViewModel.swift
//  微博
//
//  Created by 余仿 on 16/4/11.
//  Copyright © 2016年 YF. All rights reserved.
//

import UIKit

class YFStatusListViewModel: NSObject {

    /// ViewModel 持有 Model
    var statusViewModelArray:[YFStatusViewModel] = [YFStatusViewModel]()


    func loadWeiBoInfo(isPullUp: Bool,finished:(isSuccess:Bool) -> ()){

        let token = YFViewModel.sharedViewModels.userAccount?.access_token
                //token可能为nil
                guard let _ = token else{
                    //token没有值,说明userAccount为nil,说明沙盒中没有数据,说明未登录,如果未登录,肯定是引导界面,然而,调到这里来,说明是已经登录,那么token一定有值,并且没有过期
                    finished(isSuccess: false)

                    return
                }
        
        var max_id:Int64 = 0

        var since_id:Int64 = 0

        if isPullUp{

           max_id = statusViewModelArray.last?.statusList?.id ?? 0
        }else{
            //传入最新一条数据的ID
            since_id = statusViewModelArray.first?.statusList?.id ?? 0

        }


        HMNetworkTools.sharedTools.loadWeiBoInfo(token!,since_id: since_id,max_id: max_id){ (result, error) -> () in

            //请求失败
            if error != nil{
                //TODO:提示错误
                finished(isSuccess: false)
                return;
            }
            //请求成功
            //将AnyObejct转成字典
            let rootDict = result as! [String:AnyObject]
            //根据键获取需要的字典数组
            let statusArray_dict = rootDict["statuses"] as! [[String:AnyObject]]

            //遍历字典数组,字典转模型

            //可变的模型数组
            var tempArray = [YFStatusViewModel]()

            for  statusDict in statusArray_dict{

                let statusList =  YFStatusList(dict: statusDict)

                //字典转模型并添加到模型数组中
                tempArray.append(YFStatusViewModel(statusList: statusList))

            }

            //赋值给模型数组
            if isPullUp{

                self.statusViewModelArray = self.statusViewModelArray + tempArray
            }else
            {
                self.statusViewModelArray = tempArray + self.statusViewModelArray
            }
            //回调,刷新tableView
            finished(isSuccess: true)
        }
    }
    
}
